import React, { useState, useLayoutEffect } from 'react';
import {
  getAllProcess,
} from '@/services/baseData/plantCapacityBase';
import {
  getAllPlantCapacityCalendar,
  getPlantCapacityBase,
} from '@/services/product/plantCapacityCalendar';
import {
  Button,
  Form,
  Select,
  Row,
  Col,
  Spin,
} from 'antd';
import { DualAxes } from '@ant-design/charts';
import '../product/product.module.less';


const PlantCapacityBaseStatisticsTable: React.FC<{}> = (props) => {


  const [form] = Form.useForm();
  const [uvData, setuvData] = useState([]);
  const [transformData, settransformData] = useState([]);
  const [optionsProcess, setoptionsProcess] = useState([]); //工序下拉框用到
  const [loading, setLoading] = useState(false); //加载动画
  const [maxdata, setmaxdata] = useState<number>();//y轴最大值
  const initialForm = {
    date: '10',
    process: 'all',
  }

  useLayoutEffect(() => {
    const initialGraph = async () => {
      setLoading(true);
      await getprocess();
      await get_select();
      await dealwith_data();
      setLoading(false);
    };
    initialGraph();
  },[]);

  const config = {
    data: [uvData, transformData],
    xField: 'time',
    yField: ['计划产能', 'count'],
    yAxis: {
      // 格式化左坐标轴
      计划产能: {
        min: 0,
        max: maxdata,
      },
      // 隐藏右坐标轴
      count: {
        min: 0,
        max: maxdata,
        show: false,
      }
    },
    geometryOptions: [
      {
        geometry: 'column',
        columnWidthRatio: 0.4,
      },
      {
        geometry: 'line',
        seriesField: 'name',
      },
    ],
  };

  //获取工序
  const getprocess = async () => {
    const getprocesslist = await getAllProcess(null);
    const processOptionContract: ((prevState: never[]) => never[]) | { value: any; label: any }[] =
      [];
    getprocesslist.data.map((item: any, index: any) => {
      processOptionContract.push({ value: item.processCode, label: item.processName });
    });
    setoptionsProcess(processOptionContract);
  };

  const get_select = async () => {
    // 获取工序（下拉框）tab3
    const getprocesslist = await getAllProcess(null);
    const processOptionContract: ((prevState: never[]) => never[]) | { value: any; label: any }[] =
      [];
    getprocesslist.data.map((item: any, index: any) => {
      processOptionContract.push({ value: item.id, label: item.processName });
    });
    setoptionsProcess(processOptionContract);
  };

  const dealwith_data = async () => {
    // 初始化柱状数据
    const theparam = {
      date: new Date().getTime(),
      processId: '',
      range: 10,
    };
    const columnardata = await getAllPlantCapacityCalendar(theparam);
    const thedata: ((prevState: never[]) => never[]) | { time: any; 计划产能: any }[] = [];
    columnardata.data.map((item: any, index: any) => {
      thedata.push({ time: item.date, 计划产能: item.capacityLoad });
    });
    setuvData(thedata);
    // 计算柱状数据最大值
    var max_col = Math.max.apply(Math, columnardata.data.map(function (item:any){
      return item.capacityLoad;
    }));
    // 初始化横线数据
    const basicsdata = await getPlantCapacityBase({ processId: null });
    const thedata_basic:
      | ((prevState: never[]) => never[])
      | { time: any; count: any; name: string }[] = [];
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({
        time: item.date,
        count: basicsdata.data.normalCapacity,
        name: '正常产能',
      });
    });
    /*     columnardata?.data.map((item: any, index: any) => {
    /*     columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({
        time: item.date,
        count: basicsdata.data.overtimeCapacity,
        name: '加班产能',
      });
    }); */
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({
        time: item.date,
        count: basicsdata.data.totalCapacity,
        name: '总产能（含加班产能）',
      });
      thedata_basic.push({
        time: item.date,
        count: basicsdata.data.totalCapacity,
        name: '总产能（含加班产能）',
      });
    });
    settransformData(thedata_basic);
    // 保存y轴数据最大值
    setmaxdata(Math.max(max_col,basicsdata.data.totalCapacity,basicsdata.data.normalCapacity));
  };

  const handleSubmit_data = async () => {
    const res = form.getFieldsValue();
    console.log(res);
    // 更新柱状数据
    const theparam = {
      date: new Date().getTime(),
      processId: res.process == 'all' ? 'null' : res.process,
      range: res.date == undefined ? 10 : res.date,
    };
    console.log(theparam);
    const columnardata = await getAllPlantCapacityCalendar(theparam);
    const thedata = [];
    columnardata.data.map((item: any, index: any) => {
      thedata.push({ time: item.date, 计划产能: item.capacityLoad });
    });
    setuvData(thedata);
    // 柱状数据最大值
    var max_col = Math.max.apply(Math, columnardata.data.map(function (item:any){
      return item.capacityLoad;
    }));
    // 更新横线数据
    const basicsdata = await getPlantCapacityBase({
      processId: res.process == 'all' ? 'null' : res.process,
    });
    const thedata_basic = [];
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({
        time: item.date,
        count: basicsdata.data.normalCapacity,
        name: '正常产能',
      });
    });
    /*     columnardata?.data.map((item: any, index: any) => {
          thedata_basic.push({
            time: item.date,
            count: basicsdata.data.overtimeCapacity,
            name: '加班产能',
          });
        }); */
    columnardata?.data.map((item: any, index: any) => {
      thedata_basic.push({ time: item.date, count: basicsdata.data.totalCapacity, name: '总产能（含加班产能）' });
    });
    settransformData(thedata_basic);
    // 保存数据最大值
    setmaxdata(Math.max(max_col,basicsdata.data.totalCapacity,basicsdata.data.normalCapacity));
  };

  /*   function initialize() {
      getprocess();
      get_select();
      dealwith_data();
    } */


  return (
    <Spin spinning={loading}>
    <div className="figure">
      <Form
        name="wrap"
        form={form}
        // labelCol={{ flex: '110px' }}
        labelAlign="right"
        labelWrap
        // wrapperCol={{ flex: 1 }}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 12 }}
        colon={false}
        initialValues={initialForm}
      >
        <Row justify="center" gutter={[50, 0]}>
          <Col span={10}>
            <Form.Item label="时间" name="date">
              <Select
                placeholder="请选择时间"
                onChange={(value) => { handleSubmit_data() }}
                options={[
                  { value: '10', label: '10' },
                  { value: '20', label: '20' },
                  { value: '30', label: '30' },
                ]}
              />
            </Form.Item>
          </Col>
          <Col span={10}>
            <Form.Item name="process" label="工序">
              <Select
                placeholder="请选择工序"
                onChange={(value) => { handleSubmit_data() }}
                options={[{ value: 'all', label: '全部' },...optionsProcess]}
              />
            </Form.Item>
          </Col>
          {/*             <Col span={4}>
              <Button
                type="primary"
                onClick={() => {
                  handleSubmit_data();
                }}
              >
                确定
              </Button>
            </Col> */}
        </Row>
      </Form>
      {/* 统计图 */}
      <div>
        {' '}
        <DualAxes {...config} />
      </div>
    </div>
    </Spin>
  )

};
export default PlantCapacityBaseStatisticsTable;